package forum.dao;

import java.io.Serializable;
import java.util.List;

import org.hibernate.Query;
import org.hibernate.Session;
import org.hibernate.SessionFactory;
import org.hibernate.Transaction;

import forum.bean.ForumBean;

public class ForumDAO implements Serializable {

	public boolean adicionar(ForumBean forumBean) {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			Transaction transaction = session.beginTransaction();
			
			session.save(forumBean);
			
			transaction.commit();
			session.close();
			
			return true;
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return false;
	}
	
	public ForumBean get(int codigo) {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			
			Query query = session.getNamedQuery("forum_codigo");
			query.setParameter("CODIGO", codigo);
			
			List<ForumBean> lista = query.list();
			
			session.close();
			
			if (lista.size() > 0) {
				return lista.get(0);
			}
			
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return null;
	}
	
	public List<ForumBean> getLista() {
		try {
			SessionFactory sessionFactory = Sessao.getSessionFactory();
			Session session = sessionFactory.openSession();
			
			List<ForumBean> lista = session.getNamedQuery("forum_titulo").list();
			
			session.close();
			
			if (lista.size() > 0) {
				return lista;
			}
			
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return null;
	}
	
	public static void main(String[] args) {
		if (new ForumDAO().get(1) == null) {
			System.out.println("Resultado foi nulo!");
		}
	}
}
